#include "StdAfx.h"
#include "HttpConnect.h"

// use for CHttpSession
#include "HttpSession.h"

namespace HttpProtocol
{

CHttpConnect::CHttpConnect(CHttpSession* pSession, LPCSTR pstrServer,
		DWORD dwFlags,
		INTERNET_PORT nPort/* = INTERNET_INVALID_PORT_NUMBER*/,
		LPCSTR pstrUserName/* = NULL*/,
		LPCSTR pstrPassword/* = NULL*/,
		DWORD_PTR dwContext/* = 1*/)
{
	_ASSERT(pSession != NULL);
	_ASSERT(pstrServer != NULL);

	m_hConnection = InternetConnectA((HINTERNET)*pSession, pstrServer,
		nPort, pstrUserName, pstrPassword, INTERNET_SERVICE_HTTP,
		dwFlags, dwContext);

	if (m_hConnection == NULL)
	{
		throw CHttpException(GetLastError());
	}
}

CHttpConnect::~CHttpConnect(void)
{
}

CHttpStream* CHttpConnect::OpenRequest(LPCSTR pstrVerb, LPCSTR pstrObjectName,
	LPCSTR pstrReferer/* = NULL*/,DWORD_PTR dwContext/* = 1*/,
	LPCSTR* ppstrAcceptTypes/* = NULL*/, LPCSTR pstrVersion/* = NULL*/,
	DWORD dwFlags/* = INTERNET_FLAG_EXISTING_CONNECT*/)
{
	_ASSERT(m_hConnection != NULL);
	_ASSERT((dwFlags & INTERNET_FLAG_ASYNC) == 0);

	if (pstrVersion == NULL)
		pstrVersion = HTTP_VERSIONA;

	HINTERNET hFile;
	hFile = HttpOpenRequestA(m_hConnection, pstrVerb, pstrObjectName,
		pstrVersion, pstrReferer, ppstrAcceptTypes, dwFlags, dwContext);
	if (hFile == NULL)
	{
		throw CHttpException(GetLastError());
	}

	return new CHttpStream(hFile, pstrVerb, pstrObjectName, this);
}

BOOL CHttpConnect::Release(void)
{
	return InternetCloseHandle(m_hConnection);
}

}